package com.bootlever.framework.fastdfs.templates;

import com.bootlever.framework.common.utils.FileUtils;
import com.bootlever.framework.common.utils.StringUtils;
import com.bootlever.framework.fastdfs.properties.FastdfsProperties;
import org.apache.commons.io.IOUtils;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.InetSocketAddress;

public class FastdfsTemplate {

    private static final Logger logger = LoggerFactory.getLogger(FastdfsTemplate.class);

    private StorageClient1 storageClient1;

    public FastdfsTemplate(FastdfsProperties fastdfsProperties) throws IOException {
        ClientGlobal.setG_connect_timeout(fastdfsProperties.getConnectTimeout());
        ClientGlobal.setG_network_timeout(fastdfsProperties.getNetworkTimeout());
        ClientGlobal.setG_anti_steal_token(fastdfsProperties.getHttp().isAntiStealToken());
        ClientGlobal.setG_charset(fastdfsProperties.getCharset());
        ClientGlobal.setG_secret_key(fastdfsProperties.getHttp().getSecretKey());
        ClientGlobal.setG_tracker_http_port(fastdfsProperties.getHttp().getTrackerHttpPort());
        if (StringUtils.isNotBlank(fastdfsProperties.getTrackerServer())){
            String[] arr = fastdfsProperties.getTrackerServer().split(",");
            InetSocketAddress[] trackerServers = new InetSocketAddress[arr.length];
            for (int i = 0; i < arr.length; i ++){
                String address = arr[i];
                String[] ipPort = address.split(":");
                trackerServers[i] = new InetSocketAddress(ipPort[0],Integer.parseInt(ipPort[1]));
            }
            ClientGlobal.setG_tracker_group(new TrackerGroup(trackerServers));
        }
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        StorageServer storageServer = null;
        storageClient1 = new StorageClient1(trackerServer,storageServer);
    }

    /**
     * 上传
     * @param path
     * @return
     */
    public String upload(String path) throws Exception {
        File file = new File(path);
        FileInputStream fis = null;
        try {
            NameValuePair[] meta_list = null;
            fis = new FileInputStream(file);
            byte[] file_buff = null;
            if (fis != null) {
                int len = fis.available();
                file_buff = new byte[len];
                fis.read(file_buff);
                String fileId  =storageClient1.upload_file1(file_buff, FileUtils.getFileExt(path), meta_list);
                return fileId;
            }
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch(IOException e) {
                    logger.error("关闭失败",e);
                }
            }
        }
        return null;
    }

    /**
     * 删除
     * @param groupName
     * @param path
     * @return
     */
    public int delete(String groupName, String path) throws Exception{
        int result = storageClient1.delete_file(groupName == null? "group1" : groupName, path);
        return result;
    }

    /**
     * 删除（根据文件id）
     * @param fileId
     * @return
     */
    public int delete(String fileId) throws Exception {
        int result = storageClient1.delete_file1(fileId);
        return result;
    }

    /**
     * 更新文件
     * @param oldFileId
     * @param path
     * @return
     */
    public String modify(String oldFileId,String path) throws Exception {
        String fileid = null;
        //先上传
        fileid = upload(path);
        if (fileid == null) {
            return null;
        }
        //再删除
        int delResult = delete(oldFileId);
        if (delResult != 0) {
            return null;
        }
        return fileid;
    }

    /**
     * 下载
     * @param fileId
     * @return
     */
    public InputStream download(String fileId) throws Exception {
        byte[] bytes = storageClient1.download_file1(fileId);
        InputStream inputStream = new ByteArrayInputStream(bytes);
        return inputStream;
    }

    /**
     * 下载
     * @param fileId
     * @param localLocation
     * @return
     */
    public String download(String fileId, String localLocation) throws Exception {
        File file = new File(localLocation);
        InputStream in = this.download(fileId);
        byte[] bytes = IOUtils.toByteArray(in);
        org.apache.commons.io.FileUtils.writeByteArrayToFile(file,bytes);
        return localLocation;
    }

}
